/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package portal.system.inzerat;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID;
import portal.system.inzerat.service.UploadInzeratService;

/**
 *
 * @author Riso
 */
@WebServlet(name = "vlozInzerat", urlPatterns = {"/vlozInzerat"})
@MultipartConfig(location = "C:/tmp", maxFileSize = 10485760L)
public class vlozInzerat extends HttpServlet {

    String driver = portal.constants.Database.DATABASE_DRIVER;
    Connection con = null;
    String userName = portal.constants.Database.DATABASE_USER;
    String password = portal.constants.Database.DATABASE_PASSWORD;
    String URL = portal.constants.Database.DATABASE_URL;
    HttpSession session;
    String sql;
    PrintWriter out;
    Inzerat inzerat;

    @Override
    public void init() {
        try {
            super.init();
            Class.forName(driver);
            con = DriverManager.getConnection(URL, userName, password);
        } catch (Exception ex) {
        }
    }

    private void vypisForm(HttpServletRequest request) {
        try {

            Statement stmt;
            ResultSet rs;
            stmt = con.createStatement();
            rs = stmt.executeQuery("select nazov_kategorie, id_kategorie from kategorie order by nazov_kategorie asc");
            out.println("<form action=\"vlozInzerat\" method=\"post\"  name=\"form1\" id=\"form1\" ENCTYPE=\"multipart/form-data\">\n"
                    + "  <p>\n");
            out.println("    <label for=\"select1\">Kategória</label><span style=\"color: #900;\">*</span>\n"
                    + "    <br />\n"
                    + "    <select name=\"select1\" onchange=\"this.form.submit()\" style=\"width:150px\" id=\"select1\">\n"
                    + "        <option value=\"\"> </option> \n"
                    + "        \n");
            //kategórie
            while (rs.next()) {
                out.println("<option value=\"" + rs.getString("id_kategorie") + "\">" + rs.getString("nazov_kategorie") + " </option> \n");
            }
            out.println("</select>\n"
                    + "    <br />\n"
                    + "    <label for=\"select2\">Podkategória</label><span style=\"color: #900;\">*</span>\n"
                    + "    <br />\n"
                    + "<select name=\"select2\" style=\"width:150px\" id=\"select2\">\n");

            out.println("</select>\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void vypisKoniecFormu(HttpServletRequest request) {
        out.println("<br />\n");
        out.println("    <label for=\"textfield1\">Nazov Inzerátu:<span style=\"color: #900;\">*</span><br />\n"
                + "    </label>\n");

        out.println("    <input type=\"text\" name=\"textfield1\" id=\"textfield1\" />\n");
        out.println("    <br />\n"
                + "    <label for=\"popis\" style=\"vertical-align:top\">Popis Inzerátu:<span style=\"color: #900;\">*</span><br />\n"
                + "    </label>\n"
                + "    <textarea name=\"popis\" maxlength=\"1000\" style=\"height:150px;max-width: 550px;max-height: 150px;\" id=\"popis\" cols=\"70\" rows=\"5\"></textarea>\n"
                + "    <br />\n"
                + "    <label for=\"cena1\">Cena:</label>\n"
                + "    <br />\n"
                + "    <input type=\"text\" name=\"cena1\" id=\"cena1\" onkeypress=\"validate(event)\" /><span style=\"color: #900;\">*</span>\n"
                + "    €<br />\n"
                + "    <label for=\"fileinput1\">Vložiť obrázok:</label>\n"
                + "    <br />\n"
                + "<input type=\"file\" name=\"fileinput1\" id=\"fileinput1\" />\n"
                + "    <br />\n"
                + "<input type=\"file\" name=\"fileinput2\" id=\"fileinput2\" />\n"
                + "    <br />\n"
                + "<input type=\"file\" name=\"fileinput3\" id=\"fileinput3\" />\n"
                + "    <br />\n"
                + "<input type=\"file\" name=\"fileinput4\" id=\"fileinput4\" />\n"
                + "    <br />\n"
                + "<input type=\"file\" name=\"fileinput5\" id=\"fileinput5\" />\n"
                + "    <br />\n"
                + "    <br />\n"
                + "    <br />\n");
        if (session.getAttribute("id_usera") != null) {
            System.out.println("prihlásený user");
        } else {
            //osobné údaje
            out.println("    <br />\n"
                    + "    <label for=\"meno\">Meno:</label><span style=\"color: #900;\">*</span>\n"
                    + "    <br />\n"
                    + "  <input type=\"text\" name=\"meno\" id=\"meno\" />\n"
                    + "    <br />\n"
                    + "    <label for=\"heslo1\">Heslo:</label><span style=\"color: #900;\">*</span>\n"
                    + "    <br />\n"
                    + "<input type=\"password\" name=\"heslo1\" id=\"heslo1\" />\n"
                    + "    <br />\n"
                    + "    <label for=\"email\">E-mail:<span style=\"color: #900;\">*</span><br />\n"
                    + "    </label>\n"
                    + "    <input type=\"text\" name=\"email\" id=\"email\" />\n");

            //TODO: combobox na vybratie kraju a mesta
            out.println("    <br />\n"
                    + "    <label for=\"adresa\">Adresa:</label>\n"
                    + "    <br />\n"
                    + "  <input type=\"text\" name=\"adresa\" id=\"adresa\" />\n");
        }
        out.println("    <br />\n"
                + "    <input type=\"submit\" name=\"submit1\" id=\"submit1\" value=\"Odoslať\" />\n"
                + "    <br />\n"
                + "  </p>\n"
                + "</form>\n");
        out.println("</br></br>");
    }


    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected synchronized void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        session = request.getSession();
        out = response.getWriter();
        inzerat = new Inzerat();
        try {            
                if (request.getParameter("select1") != null && !request.getParameter("select1").isEmpty()) {
                    vypisform(request.getParameter("select1"), request);
                    
                } else if (request.getParameter("select1") == null || request.getParameter("select1").isEmpty()) {
                    vypisForm(request);
                    
                }
                try {
                    if(request.getParameter("textfield1")!=null){
                     MultipartMap map = new MultipartMap(request, this);
                    String contextPath = getServletContext().getRealPath("/");
                    System.out.println("cesta: "+contextPath);
                    inzerat.setAdresa(map.getParameter("adresa"));
                    System.out.println(map.getParameter("adresa"));
                    if(!map.getParameter("cena1").isEmpty()){
                    inzerat.setCena(Integer.parseInt(map.getParameter("cena1")));
                    }
                    inzerat.setDatum_pridania(new java.sql.Timestamp(System.currentTimeMillis()));
                    inzerat.setEmail(map.getParameter("email"));
                    inzerat.setHeslo(map.getParameter("heslo1"));
                    inzerat.setMesto(map.getParameter("mesto"));
                    inzerat.setMeno(map.getParameter("meno"));
                    if(!map.getParameter("cena1").isEmpty()){
                    inzerat.setNazov_inzeratu(map.getParameter("textfield1"));
                    }
                    inzerat.setText_inzeratu(map.getParameter("popis"));
                    inzerat.setObrazok1(map.getFile("fileinput1"));
                    inzerat.setObrazok2(map.getFile("fileinput2"));
                    inzerat.setObrazok3(map.getFile("fileinput3"));
                    inzerat.setObrazok4(map.getFile("fileinput4"));
                    inzerat.setObrazok5(map.getFile("fileinput5"));
                    System.out.println(map.getParameter("textfield1"));
                    System.out.println(map.getFile("fileinput1"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            
            if (inzerat.odoslat()) {
                UploadInzeratService upload = new UploadInzeratService(inzerat);
                upload.odoslatInzerat();
            }
            vypisKoniecFormu(request);
        } finally {
            response.sendRedirect("vlozInzerat.jsp?select1="+request.getParameter("select1"));
        }
    }

    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void vypisform(String parameter, HttpServletRequest request) {
        try {

            Statement stmt;
            ResultSet rs;
            stmt = con.createStatement();
            rs = stmt.executeQuery("select nazov_kategorie, id_kategorie from kategorie order by nazov_kategorie asc");
            out.println("<form action=\"vlozInzerat\" method=\"post\" name=\"form1\" ENCTYPE=\"multipart/form-data\" id=\"form1\">\n"
                    + "  <p>\n"
                    + "    <label for=\"select1\">Kategória</label><span style=\"color: #900;\">*</span>\n"
                    + "    <br />\n"
                    + "    <select name=\"select1\" onchange=\"this.form.submit();\" style=\"width:150px\" id=\"select1\">\n"
                    + "        <option value=\"\"> </option> \n"
                    + "        \n");
            //kategórie
            while (rs.next()) {
                if (parameter.equals(rs.getString("id_kategorie"))) {
                    out.println("<option selected=\"selected\" value=\"" + rs.getString("id_kategorie") + "\">" + rs.getString("nazov_kategorie") + " </option> \n");
                } else {
                    out.println("<option value=\"" + rs.getString("id_kategorie") + "\">" + rs.getString("nazov_kategorie") + " </option> \n");
                }
            }
            out.println("</select>\n"
                    + "    <br />\n"
                    + "    <label for=\"select2\">Podkategória</label><span style=\"color: #900;\">*</span>\n"
                    + "    <br />\n"
                    + "<select name=\"select2\" style=\"width:150px\" id=\"select2\">\n");
            vypisdruhySelect(parameter);
            out.println("</select>\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void vypisdruhySelect(String parameter) {
        try {

            Statement stmt;
            ResultSet rs;
            stmt = con.createStatement();
            rs = stmt.executeQuery("select nazov_podkategorie, id_podkategorie from podkategorie where id_kategorie=" + parameter + " order by nazov_podkategorie asc");
            out.println("<option value=\"\"> </option> \n");
            while (rs.next()) {

                out.println("<option value=\"" + rs.getString("id_podkategorie") + "\">" + rs.getString("nazov_podkategorie") + " </option> \n");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    private void nacitajUseraZDB() {
        try {

            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select * from user where id_usera =" + session.getAttribute("id_usera"));
            rs.next();
            inzerat.setMeno(rs.getString("meno"));
            inzerat.setEmail(rs.getString("email"));
            inzerat.setId_mesta(Integer.parseInt(rs.getString("id_mesta")));
            inzerat.setAdresa(rs.getString("adresa"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
